angular.module('module.advertisement', [
        "ngCookies",'ui.bootstrap', 'ngAnimate'
    ])
    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $stateProvider
        //首页
            .state('botMenu.advertisement', {
                url: '/advertisement',
                templateUrl: 'view/advertisement/advertisement.html',
                controller: 'AdvertisementController'
            })

            .state('botMenu.market', {
                url: '/market/:marketid',
                templateUrl: 'view/advertisement/market.html',
                controller: 'MarketController'
            })

            .state('botMenu.advertisecenter', {
                url: '/advertisecenter',
                templateUrl: 'view/advertisement/advertisecenter.html',
                controller: 'AdvertiseCenterController'
            })
            .state('botMenu.advertisedetail', {
                url: '/advertisedetail/:advid',
                templateUrl: 'view/advertisement/advertisedetail.html',
                controller: 'AdvertiseDetailController'
            })
            .state('botMenu.advertisementform',{
                url:'/advertisementform',
                templateUrl:'view/advertisement/advertisementform.html',
                controller:'AdvertisementFormController'
            })
    }])

    .controller('AdvertisementController', ['$scope', '$state', 'MarketService', 'LoginService', function ($scope, $state, MarketService, LoginService) {
        //获取店铺
        MarketService.get().$promise.then(function (data) {
            $scope.Markets = data;
            getaddr($scope.Markets,0);

            function getaddr(list, i) {
                if (i >= list.length) {
                    return
                }
                var item = list[i];
                regeocoder(item,function (status, result) {
                    console.log(result);
                    console.log(status);
                    $scope.$apply(function () {
                        if (status == 'complete') {
                            if (result.info == 'OK') {
                                item.addr = result.regeocode.addressComponent.city
                                console.log(item.addr);
                            }
                            else {
                                item.addr = "无地址";
                            }
                        }
                        else {
                            console.log("222");
                            item.addr = "无地址";
                        }
                    });
                    //$scope.markets.push(item);
                    getaddr(list, i + 1);
                    //data[i].addr = result.regeocode.addressComponent.city
                    //console.log(data)
                })


            }
            console.log($scope.Markets)

            $scope.Markets.sort(function(a,b){
                return b.mName- a.mName;
            });
            var url = window.location.href;
            var page = {
                name: "广告投放",
                url: url
            };
            $scope.pageList = LoginService.SavePageList(page);
        });
        //搜索
        $scope.shopSearch = '';
        var shopButton = document.getElementById("shopSearchButton");
        $scope.importChange = function () {
            if ($scope.shopSearch != '') {
                shopButton.removeAttribute("disabled", "disabled");
                $(shopButton).addClass('adsearch-but');
            } else {
                shopButton.setAttribute("disabled", "disabled");
                $(shopButton).removeClass('adsearch-but');
            }
        };

        $scope.marketFilter = {};
        $scope.typeFilter = function (type) {
            if (type) {
                $scope.marketFilter.mType = type;
            } else {
                $scope.marketFilter.mType = "";
            }
        }
        $scope.levelFilter = function (level) {
            if (level) {
                $scope.marketFilter.mLevel = level;
            } else {
                $scope.marketFilter.mLevel = "";
            }
        };
        $scope.nameFilter = function (name) {
            if (name) {
                $scope.marketFilter.mName = name;
            } else {
                $scope.marketFilter.mName = "";
            }
        }
        $scope.orderBy = function (data, updown) {
            switch (data){
                case "price":
                    if(updown){
                        $scope.Markets.sort(function(a,b){
                            return b.mUnitprice*b.mLablenum-a.mUnitprice*a.mLablenum;
                        });
                    }else{
                        $scope.Markets.sort(function(a,b){
                            return a.mUnitprice*a.mLablenum-b.mUnitprice*b.mLablenum;
                        });
                    }
                    break;
                case "mAdsum":
                    if(updown){
                        $scope.Markets.sort(function(a,b){
                            return b.mAdsum-a.mAdsum;
                        });
                    }
                    break;
                default:
                    $scope.Markets.sort(function(a,b){
                        return b.mName- a.mName;
                    });
                    break;
            }
        }

    }])
    //轮播
    .controller('CarouselDemoCtrl', function ($scope) {
        $scope.myInterval = 3000;
        $scope.noWrapSlides = false;
        var slides = $scope.slides = [];
        $scope.addSlide = function () {
            var newWidth = 600 + slides.length + 1;
            slides.push({
                text: '',
            });
            slides.push({

                text: '',
            });
            slides.push({

                text: '',
            });
            slides.push({

                text: '',
            });
        };
        $scope.addSlide();
    })


   /* .controller('AdvertisementFormController', ['$scope', '$state', '$stateParams', '$cookieStore', 'MarketService', 'RelationService', 'LoginService', 'advertisementService','OrderService',
        function ($scope, $state, $stateParams, $cookieStore, MarketService, RelationService, LoginService, advertisementService,OrderService) {
            $(document).scrollTop(0);
            var mId = $stateParams.marketid;
            var user = $cookieStore.get("_user");
            $scope.timeList = [];
            //无效时间段
            $scope.disabledTime = function () {
                var counts;
                // var dateMin='2016-12-01 00:00:00';
                // var dateStart =js_toStr_time(dateMin);                           //时间戳格式时间
                // var dateMax='2016-12-31 23:59:59';
                // var dateEnd = js_toStr_time(dateMax);                             //时间戳格式时间
                var now = new Date();
                var year = now.getFullYear();
                var month = now.getMonth() + 1;
                var date = now.getDate();
                var dateMin = year + '-' + month + '-' + date + ' 00:00:00';
                var dateStart = js_toStr_time(dateMin);      //当前时间的时间戳格式
                var dateEnd;                                //最大时间戳即最大的广告结束时间时间戳
                $scope.marketList = RelationService.getbymid(mId);
                $scope.marketList.$promise.then(function (data) {
                    if (data.length == 0) {
                        counts = new Array(1);
                    } else {
                        //获取最大的广告结束时间时间戳
                        dateEnd = $scope.marketList[0].aEndtime;
                        for (var i = 1; i < $scope.marketList.length; i++) {
                            if (dateEnd < $scope.marketList[i].aEndtime) {
                                dateEnd = $scope.marketList[i].aEndtime;
                            } else {
                            }
                        }
                        var count = dateEnd - dateStart + 1;
                        var len = Math.round(count / (60 * 60 * 24 * 1000));
                        counts = new Array(1);
                        counts = new Array(len);
                        counts.fill(0);
                    }
                    //根据mid获取相应的记录列表
                    $scope.marketList = RelationService.getbymid(mId);
                    $scope.marketList.$promise.then(function (data) {
                        //获取需要自增的区间
                        for (var i = 0; i < $scope.marketList.length; i++) {
                            if ($scope.marketList[i].aStarttime < dateStart && dateStart < $scope.marketList[i].aEndtime) {
                                var x = 0;
                                var y = $scope.marketList[i].aEndtime - dateStart;
                                var z = Math.round(y / (60 * 60 * 24 * 1000));
                                //console.log(x+'-'+z);
                                //调用区间自增方法
                                addCount(x, z)
                            } else if (dateStart <= $scope.marketList[i].aStarttime) {
                                var a = $scope.marketList[i].aStarttime - dateStart;
                                var b = $scope.marketList[i].aEndtime - dateStart;
                                var c = Math.round(a / (60 * 60 * 24 * 1000));
                                var d = Math.round(b / (60 * 60 * 24 * 1000));
                                //调用区间自增方法
                                addCount(c, d)
                            } else {
                            }
                        }
                        for (var i = 0; i < counts.length; i++) {
                            var oneDay = 86400000; //一天的毫秒数
                            var time1, time2;
                            if (counts[i] == 10) {    //10条
                                time1 = dateStart + i * oneDay; //当天的00:00:00
                                time2 = time1 + oneDay - 1000;  //当天的23:59:59
                                $scope.timeList.push({
                                    'start': time1,
                                    'end': time2
                                })
                            } else {

                            }
                        }
                    });
                })
                //区间[x,y)计数增加
                function addCount(x, y) {
                    for (x; x < y; x++) {
                        counts[x]++;
                    }
                }

                //时间格式2014-02-02 14:10:00改成时间戳(13位)
                function js_toStr_time(str_time) {
                    var date = new Date(str_time.replace(/-/g, '/'));
                    return date.getTime();
                }
            }
            $scope.disabledTime();
            // //检查时间是否在不可选的时间段里面
            function check() {
                if ($scope.timeList.length == 0) {
                    return true;
                } else {
                    for (var i = 0; i < $scope.timeList.length; i++) {
                        if ($scope.endtime > $scope.timeList[i].start && $scope.starttime < $scope.timeList[i].end) {
                            return false;
                            break;
                        } else {
                            if (i >= $scope.timeList.length - 1) {
                                return true
                            } else {
                                continue;
                            }
                        }
                    }
                }
            }
            $('#datetimepicker').datetimepicker({
                minView: "month",
                format: "yyyy-MM-dd 00:00:00",
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left",
            }).on('changeDate', function (ev) {
                $scope.starttime2 = ev.date.valueOf();
                $scope.starttime1 = time($scope.starttime2) + ' 00:00:00';  //2016-10-10 00:00:00格式时间
                var date = new Date($scope.starttime1.replace(/-/g, '/'));
                $scope.starttime = date.getTime();                        //时间戳格式时间
            });
            $('#datetimepicker1').datetimepicker({
                minView: "month",
                format: "yyyy-MM-dd 23:59:59",
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left",
            }).on('changeDate', function (ev) {
                $scope.endtime2 = ev.date.valueOf();                        //选中的实际时间
                $scope.endtime1 = time($scope.endtime2) + ' 23:59:59'       //2016-10-10 00:00:00格式时间
                var date = new Date($scope.endtime1.replace(/-/g, '/'));
                $scope.endtime = date.getTime();                             //时间戳格式时间
            });
            $scope.submit_bind = function () {
                if ($scope.starttime == undefined) {
                    alert("未选择开始时间！");
                } else if ($scope.endtime == undefined) {
                    alert("未选择结束时间！");
                } else if ($scope.starttime > $scope.endtime) {
                    alert("结束时间不小于开始时间！");
                } else if (!check()) {
                    alert("该时间段已被预订！");
                } else {
                    $scope.relation = {};
                    $scope.relation.aStarttime = $scope.starttime;
                    $scope.relation.aEndtime = $scope.endtime;
                    $scope.relation.aId = 11;
                    $scope.relation.mId = mId;
                    /!*RelationService.add($scope.relation, function (data) {
                     alert("绑定成功！");
                     // $state.go('adv.ad');
                     }, function (data) {
                     alert("绑定失败！");
                     });*!/
                }
            };
            $scope.addTime = function () {
                if (!user) {
                    $state.go("login");//还未登录的操作；
                    return;
                }
                if ($scope.starttime == undefined) {
                    alert("未选择开始时间！");
                } else if ($scope.endtime == undefined) {
                    alert("未选择结束时间！");
                } else if ($scope.starttime > $scope.endtime) {
                    alert("结束时间不小于开始时间！");
                } else if (!check()) {
                    alert("该时间段已被预订！");
                } else {
                    //var scrollTop = document.body.offsetHeight - $(window).height();
                    //window.scrollTo(0, scrollTop);
                    $("#advadd").fadeIn(300);
                    $(".market_footer").addClass("rotate");
                }
            };
            $scope.addAdvHide = function(){
                $("#advadd").fadeOut(300);
                $(".market_footer").removeClass("rotate");
            };
            $scope.adv = {};
            $scope.adv.aType = 0;
            $scope.aTypeList = [{
                num: 0,
                name: "基础版"
            }];
            $scope.submit_adv = function (adv) {
                adv.aCreatetime = new Date();
                adv.cId = user.userid;
                $(".market_button").attr("disabled","disabled");
                advertisementService.add(adv, function (data) {
                    var remarks = "价媒平台订单";
                    if($scope.byMessage){
                        remarks = $scope.byMessage;
                    }
                    var order = {
                        "info": "价媒平台订单",
                        "remarks": remarks,
                        "createtime": new Date(),
                        "aid": data.aId,
                        "cid": user.userid,
                        "adstarttime": $scope.starttime,
                        "adendtime": $scope.endtime,
                        "marketid": mId,
                    };
                    OrderService.updateNewOrder(order,function(order){
                        $scope.qrcodeUrl = order.qrcode;
                        var _width = $("#qrcode").width();
                        var _height = $("#qrcode").height();
                        var qrcode = new QRCode(document.getElementById("qrcode"), {
                            width: _width,//设置宽高
                            height: _height
                        });
                        qrcode.makeCode($scope.qrcodeUrl);
                        var orderid = $scope.qrcodeUrl.split("orderid=")[1];
                        getOrderById(orderid);
                        $("#qrcodecontext").show();
                        $(".market_button").removeAttr("disabled");
                        $("#advadd").hide();
                        $(".market_footer").removeClass("rotate");
                    },function(){
                        $(".market_button").removeAttr("disabled");
                        $(".market_footer").removeClass("rotate");
                        alert("提交失败");
                    })
                }, function (data) {
                    $(".market_button").removeAttr("disabled");
                    $(".market_footer").removeClass("rotate");
                    alert("广告提交失败！")
                })
            };
            function getOrderById(orderid){
                OrderService.getOrderByOrderId(orderid).$promise.then(function(order){
                    if(order.orderstatus==0){
                        setTimeout(function(){
                            getOrderById(orderid)
                        },3000);
                    }else if(order.orderstatus==1){
                        alert("支付成功");
                        $state.go("botMenu.ordercenter");
                    }
                });
            }
        }])*/




    .controller('MarketController', ['$scope', '$state', '$stateParams', '$cookieStore', 'FileUpload','MarketService', 'RelationService', 'LoginService', 'advertisementService','OrderService',
        function ($scope, $state, $stateParams, $cookieStore,FileUpload, MarketService, RelationService, LoginService, advertisementService,OrderService) {
            $(document).scrollTop(0);
            var mId = $stateParams.marketid;
            var user = $cookieStore.get("_user");
            $scope.nomap=false;
            MarketService.getByid(mId).$promise.then(function (market) {
                var url = window.location.href;
                var page = {
                    name: market.mName,
                    url: url
                };
                $scope.pageList = LoginService.SavePageList(page);
                $scope.market = market;






                if (market.mLng == null || market.mLat == null) {
                   /* alert("商家未设置地址")*/
                        $scope.nomap=true;
                }
                else {
                    init(market);
                    //init(market.mLng,market.mLat,market.mAddr);
                }
            });
            $scope.timeList = [];
            //无效时间段
            $scope.disabledTime = function () {
                var counts;
                // var dateMin='2016-12-01 00:00:00';
                // var dateStart =js_toStr_time(dateMin);                           //时间戳格式时间
                // var dateMax='2016-12-31 23:59:59';
                // var dateEnd = js_toStr_time(dateMax);                             //时间戳格式时间
                var now = new Date();
                var year = now.getFullYear();
                var month = now.getMonth() + 1;
                var date = now.getDate();
                var dateMin = year + '-' + month + '-' + date + ' 00:00:00';
                var dateStart = js_toStr_time(dateMin);      //当前时间的时间戳格式
                var dateEnd;                                //最大时间戳即最大的广告结束时间时间戳
                $scope.marketList = RelationService.getbymid(mId);
                $scope.marketList.$promise.then(function (data) {
                    if (data.length == 0) {
                        counts = new Array(1);
                    } else {
                        //获取最大的广告结束时间时间戳
                        dateEnd = $scope.marketList[0].aEndtime;
                        for (var i = 1; i < $scope.marketList.length; i++) {
                            if (dateEnd < $scope.marketList[i].aEndtime) {
                                dateEnd = $scope.marketList[i].aEndtime;
                            } else {
                            }
                        }
                        var count = dateEnd - dateStart + 1;
                        var len = Math.round(count / (60 * 60 * 24 * 1000));
                        counts = new Array(1);
                        counts = new Array(len);
                        counts.fill(0);
                    }
                    //根据mid获取相应的记录列表
                    $scope.marketList = RelationService.getbymid(mId);
                    $scope.marketList.$promise.then(function (data) {
                        //获取需要自增的区间
                        for (var i = 0; i < $scope.marketList.length; i++) {
                            if ($scope.marketList[i].aStarttime < dateStart && dateStart < $scope.marketList[i].aEndtime) {
                                var x = 0;
                                var y = $scope.marketList[i].aEndtime - dateStart;
                                var z = Math.round(y / (60 * 60 * 24 * 1000));
                                //console.log(x+'-'+z);
                                //调用区间自增方法
                                addCount(x, z)
                            } else if (dateStart <= $scope.marketList[i].aStarttime) {
                                var a = $scope.marketList[i].aStarttime - dateStart;
                                var b = $scope.marketList[i].aEndtime - dateStart;
                                var c = Math.round(a / (60 * 60 * 24 * 1000));
                                var d = Math.round(b / (60 * 60 * 24 * 1000));
                                //调用区间自增方法
                                addCount(c, d)
                            } else {
                            }
                        }
                        for (var i = 0; i < counts.length; i++) {
                            var oneDay = 86400000; //一天的毫秒数
                            var time1, time2;
                            if (counts[i] >= 10) {    //10条
                                time1 = dateStart + i * oneDay; //当天的00:00:00
                                time2 = time1 + oneDay - 1000;  //当天的23:59:59
                                $scope.timeList.push({
                                    'start': time1,
                                    'end': time2
                                })
                            } else {

                            }
                        }
                    });
                })
                //区间[x,y)计数增加
                function addCount(x, y) {
                    for (x; x < y; x++) {
                        counts[x]++;
                    }
                }

                //时间格式2014-02-02 14:10:00改成时间戳(13位)
                function js_toStr_time(str_time) {
                    var date = new Date(str_time.replace(/-/g, '/'));
                    return date.getTime();
                }
            }
            $scope.disabledTime();
            // //检查时间是否在不可选的时间段里面
            function check() {
                if ($scope.timeList.length == 0) {
                    return true;
                } else {
                    for (var i = 0; i < $scope.timeList.length; i++) {
                        if ($scope.endtime > $scope.timeList[i].start && $scope.starttime < $scope.timeList[i].end) {
                            return false;
                            break;
                        } else {
                            if (i >= $scope.timeList.length - 1) {
                                return true
                            } else {
                                continue;
                            }
                        }
                    }
                }
            }
            $('#datetimepicker').datetimepicker({
                minView: "month",
                format: "yyyy-MM-dd 00:00:00",
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left",
            }).on('changeDate', function (ev) {
                $scope.starttime2 = ev.date.valueOf();
                $scope.starttime1 = time($scope.starttime2) + ' 00:00:00';  //2016-10-10 00:00:00格式时间
                var date = new Date($scope.starttime1.replace(/-/g, '/'));
                $scope.starttime = date.getTime();                        //时间戳格式时间
            });
            $('#datetimepicker1').datetimepicker({
                minView: "month",
                format: "yyyy-MM-dd 23:59:59",
                autoclose: true,
                todayBtn: true,
                pickerPosition: "bottom-left",
            }).on('changeDate', function (ev) {
                $scope.endtime2 = ev.date.valueOf();                        //选中的实际时间
                $scope.endtime1 = time($scope.endtime2) + ' 23:59:59'       //2016-10-10 00:00:00格式时间
                var date = new Date($scope.endtime1.replace(/-/g, '/'));
                $scope.endtime = date.getTime();                             //时间戳格式时间
            });
            $scope.submit_bind = function () {
                if ($scope.starttime == undefined) {
                    alert("未选择开始时间！");
                } else if ($scope.endtime == undefined) {
                    alert("未选择结束时间！");
                } else if ($scope.starttime > $scope.endtime) {
                    alert("结束时间不小于开始时间！");
                } else if (!check()) {
                    alert("该时间段已被预订！");
                } else {
                    $scope.relation = {};
                    $scope.relation.aStarttime = $scope.starttime;
                    $scope.relation.aEndtime = $scope.endtime;
                    $scope.relation.aId = 11;
                    $scope.relation.mId = mId;
                    RelationService.add($scope.relation, function (data) {
                     alert("绑定成功！");
                     // $state.go('adv.ad');
                     }, function (data) {
                     alert("绑定失败！");
                     });
                }
            };
            $scope.addTime = function () {
                if (!user) {
                    $state.go("login");//还未登录的操作；
                    return;
                }
                if ($scope.starttime == undefined) {
                    alert("未选择开始时间！");
                } else if ($scope.endtime == undefined) {
                    alert("未选择结束时间！");
                } else if ($scope.starttime > $scope.endtime) {
                    alert("结束时间不小于开始时间！");
                } else if (!check()) {
                    alert("该时间段已被预订！");
                } else {
                    //var scrollTop = document.body.offsetHeight - $(window).height();
                    //window.scrollTo(0, scrollTop);
                    $("#advadd").fadeIn(300);
                    $(".market_footer").addClass("rotate");
                }
            };
            $scope.addAdvHide = function(){
                $("#advadd").fadeOut(300);
                $(".market_footer").removeClass("rotate");
            };
            $scope.adv = {};
            $scope.adv.aType = 0;
            $scope.aTypeList = [{
                num: 0,
                name: "基础版"
            }];
            $scope.submit_adv = function (adv) {
                uploadFileToUrl($scope.moduleCarousel, 0);
                // adv.aCreatetime = new Date();
                // adv.cId = user.userid;
                // $(".market_button").attr("disabled","disabled");
                // advertisementService.add(adv, function (data) {
                //     var remarks = "价媒平台订单";
                //     if($scope.byMessage){
                //         remarks = $scope.byMessage;
                //     }
                //     var order = {
                //         "info": "价媒平台订单",
                //         "remarks": remarks,
                //         "createtime": new Date(),
                //         "aid": data.aId,
                //         "cid": user.userid,
                //         "adstarttime": $scope.starttime,
                //         "adendtime": $scope.endtime,
                //         "marketid": mId,
                //     };
                //     OrderService.updateNewOrder(order,function(order){
                //         $scope.qrcodeUrl = order.qrcode;
                //         var _width = $("#qrcode").width();
                //         var _height = $("#qrcode").height();
                //         var qrcode = new QRCode(document.getElementById("qrcode"), {
                //             width: _width,//设置宽高
                //             height: _height
                //         });
                //         qrcode.makeCode($scope.qrcodeUrl);
                //         var orderid = $scope.qrcodeUrl.split("orderid=")[1];
                //         getOrderById(orderid);
                //         $("#qrcodecontext").show();
                //         $(".market_button").removeAttr("disabled");
                //         $("#advadd").hide();
                //         $(".market_footer").removeClass("rotate");
                //     },function(){
                //         $(".market_button").removeAttr("disabled");
                //         $(".market_footer").removeClass("rotate");
                //         alert("提交失败");
                //     })
                // }, function (data) {
                //     $(".market_button").removeAttr("disabled");
                //     $(".market_footer").removeClass("rotate");
                //     alert("广告提交失败！")
                // })
            };
            function getOrderById(orderid){
                OrderService.getOrderByOrderId(orderid).$promise.then(function(order){
                    if(order.orderstatus==0){
                        setTimeout(function(){
                            getOrderById(orderid)
                        },3000);
                    }else if(order.orderstatus==1){
                        alert("支付成功");
                        $state.go("botMenu.ordercenter");
                    }
                });
            }


            // $scope.plate1 = {
            //     "type": 1,
            //     "content": [/*{"url": "", "image": "image/lunbo7.png", "alt": "", "sort": 0, "href": ""},
            //      {"url": "", "image": "image/lunbo4.png", "alt": "", "sort": 1, "href": ""},
            //      {"url": "", "image": "image/lunbo6.png", "alt": "", "sort": 2, "href": ""},*/
            //     ]
            // };
            /*$scope.imgs = [
             {url:"image/background.png"},
             {url:"image/ESLADS.png"}
             ]*/
            /* $scope.getFile = function () {
             fileReader.readAsDataUrl($scope.file, $scope)
             .then(function (result) {
             $scope.imageSrc = result;
             });
             }*/
            /*
            {
                "hpbk":[],
                "dabk":[],
                "hlogo":[],
                "habk":[]
            }
            */
            // var i=0,result="";
            // $scope.uploadFile = function(file,id){
            //     var add = document.getElementById('add');
            //     var id1="input"+id;
            //     var id2 = document.getElementById(id1).parentNode.id;
            //     var prevDiv = document.getElementById(id2);
            //     if (file.files && file.files[0]) {
            //         var reader = new FileReader();
            //         reader.onload = function(evt) {
            //             prevDiv.innerHTML = '<img src="' + evt.target.result + '" style="width: 100%;height:100%;" />' ;
            //         }
            //         addString(file);
            //         reader.readAsDataURL(file.files[0]);
            //         addchild(id);
            //     } else {
            //         prevDiv.innerHTML = '<div class="add-picture" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
            //         addString(file);
            //         addchild(id);
            //     }
            // }
            //
            // function addchild(id) {
            //     var nid=id+1;
            //     if(nid<=4) {
            //         var text = '<div id="' + nid + '" class="add-picture">' +
            //             '<div class="add-picture-add">+</div>' +
            //             '<div>添加图片</div>' +
            //             '<input file-devpayment="myFile" id="input' + nid + '" onchange="angular.element(this).scope().uploadFile(this,' + nid + ')" class="imageUploadModule" type="file" accept="image/jpg,image/jpeg,image/bmp,image/png,image/gif">' +
            //             '</div>';
            //         $("#add").append(text);
            //     }
            // }
            //
            // function addString(file) {
            //     FileUpload.uploadFileToUrl( file.files[0]).then(function (files) {
            //         if(i) {
            //             result=result+',{"url":"'+files.faddress+'","crc":11,"no":0}';
            //         }
            //         else {
            //             result='{"url":"'+files.faddress+'","crc":11,"no":0}';
            //             i++;
            //         }
            //         console.log(result);
            //     });
            // }
           /* $scope.uploadFile = function(file)  {
                console.log(file.value);
                $scope.imgs.push({
                        url:file.value
                })
                console.log($scope.imgs);
              /!*  if ($scope.myFile == undefined) {
                    alert("请选择图片！");
                    return;
                }
                var file = $scope.myFile;
                if(file.size>=409600){
                    alert("文件大小不符合要求！");
                }else {
                    fileUpload.setavatarurl($scope.imageSrc,file).then(function (data) {
                        if (data != undefined) {
                            alert("上传成功！");
                            $scope.ad.aHomepicture = data.faddress;
                        }
                    });
                }*!/
            };*/
           /* $scope.addHomepic = function(){
                $("#formDialogModule").fadeIn(300);
                $(".market_footer").removeClass("rotate");
            }*/







            $scope.qrcodehide=function () {
                $('#qrcodecontext').html('');
                $('#qrcodecontext').hide();
            }











            //图片上传
            $scope.urllist = [];
            $scope.urltest = "";

            function uploadFileToUrl(carouselList, i) {
                if (i >= carouselList.length) {
                    var detailpicture = "";
                    detailpicture = '{"hpbk":[],"dabk":[' + $scope.urltest + '],"hlogo":[],"habk":[]}';
                    // detailpicture = "{'hpbk':[],'dabk':[" + $scope.urltest + "],'hlogo':[],'habk':[]}";
                    $scope.adv.aDetailpicture = detailpicture;

                    $scope.adv.aQrcode = $scope.adv.aUrl;
                    $scope.adv.aCreatetime = new Date();
                    $scope.adv.cId = user.userid;
                    $(".market_button").attr("disabled","disabled");
                    advertisementService.add($scope.adv, function (data) {
                        var remarks = "价媒平台订单";
                        if($scope.byMessage){
                            remarks = $scope.byMessage;
                        }
                        var order = {
                            "info": "价媒平台订单",
                            "remarks": remarks,
                            "createtime": new Date(),
                            "aid": data.aId,
                            "cid": user.userid,
                            "adstarttime": $scope.starttime,
                            "adendtime": $scope.endtime,
                            "marketid": mId,
                        };
                        OrderService.updateNewOrder(order,function(order){
                            $scope.qrcodeUrl = order.qrcode;
                            var _width = $("#qrcode").width();
                            var _height = $("#qrcode").height();
                            var qrcode = new QRCode(document.getElementById("qrcode"), {
                                width: _width,//设置宽高
                                height: _height
                            });
                            qrcode.makeCode($scope.qrcodeUrl);
                            var orderid = $scope.qrcodeUrl.split("orderid=")[1];
                            getOrderById(orderid);
                            $("#qrcodecontext").show();
                            $(".market_button").removeAttr("disabled");
                            $("#advadd").hide();
                            $(".market_footer").removeClass("rotate");
                        },function(){
                            $(".market_button").removeAttr("disabled");
                            $(".market_footer").removeClass("rotate");
                            alert("提交失败");
                        })
                    }, function (data) {
                        $(".market_button").removeAttr("disabled");
                        $(".market_footer").removeClass("rotate");
                        alert("广告提交失败！")
                    })

                    return;
                }
                var carousel = carouselList[i];
                if (carousel.file && carousel.file != "") {
                    FileUpload.uploadFileToUrl(carousel.file).then(function (files) {
                        carousel.image = files.faddress;
                        $scope.urllist.push({
                            "url": files.faddress,
                            "crc": ~parseInt(files.crc32,16).toString(10),
                            "no": i
                        });
                        //图片地址的url字符串拼接
                        if (i == 0) {
                            $scope.urltest = $scope.urltest + '{"url":"' + $scope.urllist[i].url + '","crc":' + $scope.urllist[i].crc + ',"no":' + i + '}';
                        } else {
                            $scope.urltest = $scope.urltest + ',{"url":"' + $scope.urllist[i].url + '","crc":' + $scope.urllist[i].crc + ',"no":' + i + '}';
                        }
                        carousel.file = "";
                        uploadFileToUrl(carouselList, i + 1);
                    });
                } else {
                    uploadFileToUrl(carouselList, i + 1);
                }

            }

            //上传图片
            var i = 1;
            var file = "";
            $scope.moduleCarousel = [];
            var imageUploadModule = document.querySelectorAll('.imageUploadModule');
            for (var i = 0; i < imageUploadModule.length; i++) {
                imageUploadModule[i].addEventListener('change', function (e) {
                    var self = this;
                    file = this.files[0];
                    var reader = new FileReader();
                    if (file.size > 10 * 1024 * 1024) {
                        alert("上传图片最大为10M");
                        return;
                    } else {
                        if (file.size > 256 * 1024) {
                            var maxWidth = 500,
                                maxHeight = 500;
                            if (file.size > 2 * 1024 * 1024) {
                                maxWidth = 600;
                                maxHeight = 600;
                            }
                        }
                    }
                    reader.readAsDataURL(file);

                    reader.onload = function (e) {
                        var base64Img = this.result;
                        var img1 = new Image();
                        img1.src = base64Img;
                        var num = 0;

                        function ImageCompress() {
                            if (num >= 100) {
                                alert("加载失败");
                                return;
                            }
                            if ($(img1)[0].naturalWidth == 0) {
                                setTimeout(function () {
                                    num++;
                                    ImageCompress();
                                }, 100)

                            } else {
                                new ImageResizer({
                                    resizeMode: "auto",
                                    dataSource: base64Img,
                                    dataSourceType: "base64",
                                    maxWidth: maxWidth, //允许的最大宽度
                                    maxHeight: maxHeight, //允许的最大高度。
                                    onTmpImgGenerate: function (img) {
                                    },
                                    success: function (resizeImgBase64, canvas) {
                                        var blob = dataURLtoBlob(resizeImgBase64);
                                        blob.name = file['name'];
                                        file = blob;
                                        console.log(file);
                                        base64Img = resizeImgBase64;
                                        if (self.name == "single") {
                                            $scope.$apply(function () {
                                                $scope.editPlate.content.image = base64Img;
                                            });
                                        }
                                    }
                                });
                            }
                        }
                        if (self.name == "carousel") {
                            var isHad = false;
                            for (var j = 0; j < $scope.moduleCarousel.length; j++) {

                                if (base64Img == $scope.moduleCarousel[j].image) {
                                    isHad = true;
                                    alert("图片已存在！");
                                }
                            }
                            if (!isHad) {
                                var newFile = file;
                                var name = file['name']
                                var a = encodeURI(name)
                                var carousel = {
                                    "url": "",
                                    "image": base64Img,
                                    "alt": "",
                                    "sort": $scope.moduleCarousel.length + 1,
                                    "href": "",
                                    "file": newFile
                                };
                                $scope.$apply(function () {
                                    $scope.moduleCarousel.push(carousel);

                                });
                            }
                        }
                        ImageCompress();
                    };
                });
            }
            //删除上传图片
            $scope.removeCarouselImg = function (carousel) {
                var index = $scope.moduleCarousel.indexOf(carousel);
                $scope.moduleCarousel.splice(index, 1);
                for (var i = 0; i < $scope.moduleCarousel.length; i++) {
                    $scope.moduleCarousel[i].sort = i + 1;
                }
            };















            $scope.addHomepicHide = function(){
                $("#formDialogModule").fadeOut(300);
                $("#advadd").fadeOut(300);
                $(".market_footer").removeClass("rotate");
            };
            //图片上传
            // function uploadFileToUrl(carouselList,i){
            //     if(i>=carouselList.length){
            //         updatePlateByKey(false, carouselList,1);
            //         return;
            //     }
            //     var carousel = carouselList[i];
            //     if(carousel.file&&carousel.file!=""){
            //         FileUpload.uploadFileToUrl(carousel.file).then(function (files) {
            //             carousel.image = files.faddress;
            //             carousel.file = "";
            //             uploadFileToUrl(carouselList,i+1);
            //         });
            //     }else{
            //         uploadFileToUrl(carouselList,i+1);
            //     }
            // }
            // $scope.close = function (Module) {
            //     $(".popupBg").fadeOut();
            //     $(Module).fadeOut();
            // };
            // //调用更新接口
            // function updatePlateByKey(files, content,type) {
            //     var editPlate = new Object();
            //     if (files) {
            //         content.image = files.faddress;
            //     }
            //     editPlate.type = type;
            //     editPlate.accesscode = accessCode;
            //     editPlate.content = JSON.stringify(content);
            //     EntranceService.updatePlateByKey(editPlate, function (plate) {
            //         plate.content = JSON.parse(plate.content);
            //         plateType(plate);
            //         alert("修改成功");
            //         $scope.slide();
            //         $scope.close("#formDialogModule");
            //     }, function () {
            //         alert("修改失败");
            //     })
            // }
            //编辑整个轮播模块
            $scope.editModule = function (module) {
                $(".popupBg").fadeIn();
                $("#formDialogModule").fadeIn();
                $scope.edit_text = "轮播模块样式";
                $scope.moduleCarousel = [];
                for (var i = 0; i < module.content.length; i++) {
                    $scope.moduleCarousel.push(module.content[i]);
                }
                var _width = 100 * (module.content.length + 1);
                $("#fk-imgContainer").css({"width": _width | +"px"});
            };
            $scope.removeCarouselImg = function(carousel){
                var index = $scope.moduleCarousel.indexOf(carousel);
                $scope.moduleCarousel.splice(index,1);
                for(var i=0;i<$scope.moduleCarousel.length;i++){
                    $scope.moduleCarousel[i].sort = i+1;
                }
            };

        }])


    .controller('AdvertiseCenterController', ['$scope','$cookieStore','$state','advertisementService','RegisterService','LoginService', function ($scope,$cookieStore,$state,advertisementService,RegisterService,LoginService){
        if($cookieStore.get('_user') != undefined){
            var user = $cookieStore.get('_user');
            var userid = user.userid;
            RegisterService.getPower(userid).$promise.then(function (data) {
                if (data.manager == 1) {
                    $scope.advList= advertisementService.queryAllAdv();
                } else{
                    $scope.advList= advertisementService.getAdvById(userid);
                }
                var url = window.location.href;
                var page = {
                    name: "广告管理",
                    url: url
                };
                $scope.pageList = LoginService.SavePageList(page);
                $scope.currentPage = 1;
                $scope.pageSize = 8;
            })
        }else{
            $state.go("login");
        }

        //用过滤的方法切换类型

        $scope.adv = {};
        $scope.statusFilter = function(status){
            if(status!=undefined){
                $scope.adv.aProcess = status;
            }else{
                $scope.adv.aProcess = "";
            }
        };
        $scope.remove = function(adv){
            $("#remove_sure").fadeIn(300);
            $(".md-content").addClass("md-show");
            $scope.sure_remove = function(){
                advertisementService.removeByAdvid(adv.aId,function(){
                    for(var i=0;i<$scope.advList.length;i++){
                        if($scope.advList[i].aId == adv.aId){
                            $scope.advList.splice(i,1);
                            $scope.removeHide();
                            break;
                        }
                    }
                },function(){

                });
            };
        };
        $scope.aTypeList = [{
            num: 0,
            name: "基础版"
        }];
        var editAdv = {};
        $scope.edit = function(adv){
            editAdv = {};
            $("#advadd").fadeIn(300);
            $(".market_footer").addClass("rotate");
            $scope.editAdv = adv;
            for(var name in adv){
                editAdv[name] = $scope.editAdv[name];
            }
            $scope.sure_adv = function(){
                advertisementService.updataByAdvid(adv,function(){
                    $scope.addAdvHide(true);
                },function(){

                });
            };
        };
        $scope.addAdvHide = function(type){
            if(!type){
                for(var i=0;i<$scope.advList.length;i++){
                    if($scope.advList[i].aId == editAdv.aId){
                        $scope.advList[i] = editAdv;
                        break;
                    }
                }
            }
            $(".market_footer").removeClass("rotate");
            $("#advadd").fadeOut(300);
        };
        $scope.removeHide = function(){
            $("#remove_sure").fadeOut(300);
            $(".md-content").removeClass("md-show");
        };
    }])
    //广告详情页面
    .controller('AdvertiseDetailController', ['$scope','$stateParams','advertisementService', function ($scope,$stateParams,advertisementService){
        advertisementService.getAdvByAdvId($stateParams.advid).$promise.then(function(adv){
            $scope.adv = adv;
            $scope.adlinkList = {};
            if(adv.aProcess == 0){
                //$scope.adlinkList=advertisementService.invalidrelByAdvid(adv.aId);
            }else{
                advertisementService.invalidrelByAdvid(adv.aId).$promise.then(function(marketList){
                    $scope.adlinkList.invalid = marketList;
                });
                advertisementService.relationByAdvid(adv.aId).$promise.then(function(marketList){
                    $scope.adlinkList.valid = marketList;
                });
            }
        })
    }])
;